<template>
  <!-- start表单主体部分 -->
  <el-row>
    <el-col :span="24">
      <el-card style="max-width: 100%">
        <el-button type="success" style="margin: 1px;" @click="AddShowFlag = true">添加</el-button>
        <div style="display: flex; justify-content: flex-end; align-items: center;">
          <!--父分类筛选器-->
          <el-form-item style="margin-right: 10px;">
            <el-cascader
                v-model="condition.categoryId"
                :options="allParentList"
                :props="props"
                @change="selectByPage(1)"
                placeholder="请选择分类"
                clearable
                :value-on-clear="null"/>
            <!--上架下架筛选器-->
            <el-select
                v-model="condition.status"
                clearable
                placeholder="请选择是否上架"
                style="width: 150px; margin-right: 10px;"
                @change="selectByPage(1)"
            >
              <el-option label="上架" value="1"/>
              <el-option label="下架" value="0"/>
            </el-select>
            <el-input v-model="condition.name" style="width: 240px;" placeholder="输入分类名称搜索"
                      :prefix-icon="Search" @input="selectByPage(1)"/>
          </el-form-item>

        </div>
        <el-table :data="pageInfo.list" style="width: 100%; " border>
          <el-table-column prop="id" label="ID"/>
          <el-table-column prop="name" label="名称"/>
          <el-table-column prop="dscp" label="描述"/>
          <el-table-column prop="price" label="售价"/>
          <el-table-column prop="markPrice" label="标价"/>
          <el-table-column prop="purchasePrice" label="进价"/>
          <el-table-column prop="color" label="颜色"/>
          <el-table-column prop="version" label="版本"/>
          <el-table-column prop="count" label="数量" width="50px"/>
          <el-table-column prop="recom" label="是否推荐">
            <template #default="scope">
              <el-switch
                  :active-value="1" :inactive-value="0" size="small"
                  active-text="推荐" inactive-text="不推荐" inline-prompt
                  v-model="scope.row.recom" class="ml-2"
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                  @change="updateRecom(scope.row.id, scope.row.recom)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="categoryId" label="所属分类ID"/>
          <el-table-column prop="score" label="评分"/>
          <el-table-column prop="status" label="是否上架">
            <template #default="scope">
              <el-switch
                  :active-value="1" :inactive-value="0" size="large"
                  active-text="上架" inactive-text="下架" inline-prompt
                  v-model="scope.row.status" class="ml-2"
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                  @change="updateStatus(scope.row.id, scope.row.status)"
              />
            </template>
          </el-table-column>
          <el-table-column label="所属分类">
            <template #default="scope">
              <el-text class="mx-1" type="primary" v-if="scope.row.category">
                {{ scope.row.category.name }}
              </el-text>
            </template>
          </el-table-column>
          <el-table-column label="图片">
            <template #default="scope">
              <el-popover placement="right" trigger="hover" v-if="scope.row.picList.length > 0">
                <template #reference>
                  <el-image :key="index" style="width: 20px;height: 20px"
                            :src="SERVER_ADDR + '/goods/pic/' + scope.row.picList[0].url" :fit="fit"/>
                </template>
                <el-image v-for="(pic,index) in scope.row.picList" :key="index"
                          style="width: 50px;height: 50px;margin-right: 5px;"
                          :src="SERVER_ADDR + '/goods/pic/' + pic.url" :fit="fit"/>
              </el-popover>
            </template>
          </el-table-column>

          <el-table-column width="200px" label="操作">
            <template #default="scope" >
              <el-button size="small" type="success" @click="showDetailDialog(scope.row)">详情</el-button>
              <el-button size="small" type="primary" @click="selectById(scope.row.id)">编辑</el-button>
              <!-- 删除的气泡框 -->
              <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled"
                             icon-color="#626AEF" title="确定要删除吗?" @confirm="del(scope.row.id)"
                             @cancel="cancelEvent">
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row class="row-bg" justify="center">
          <el-pagination background layout="prev, pager, next" :page-count="pageInfo.pages"
                         style="margin: 10px;" page-size=5 small="true" v-model:current-page="pageInfo.pageNum"
                         @update:current-page="selectByPage"/>
        </el-row>
      </el-card>
    </el-col>
  </el-row>
  <!--   end表单主体部分-->

  <!-- start增加提示框 -->
  <div>
    <el-dialog v-model="AddShowFlag" title="添加分类" width="500">
      <el-form :rules="rules"  :model="categoryAdd">
        <el-form-item label="分类" label-width="20%">
          <el-cascader
              v-model="categoryAdd.categoryId"
              :options="allParentList"
              :props="props"
              placeholder="请选择分类"
              clearable
              :value-on-clear="null"/>
        </el-form-item>
        <el-form-item label="名称" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="categoryAdd.name"/>
        </el-form-item>
        <el-form-item label="描述" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="categoryAdd.dscp"/>
        </el-form-item>
        <el-form-item label="售价" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="categoryAdd.price"/>
        </el-form-item>
        <el-form-item label="标价" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="categoryAdd.markPrice"/>
        </el-form-item>
        <el-form-item label="进价" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="categoryAdd.purchasePrice"/>
        </el-form-item>
        <el-form-item label="颜色" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="categoryAdd.color"/>
        </el-form-item>
        <el-form-item label="版本" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="categoryAdd.version"/>
        </el-form-item>
        <el-form-item label="数量" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="categoryAdd.count"/>
        </el-form-item>
        <el-form-item label="是否推荐" label-width="20%" prop="recom">
          <el-radio-group v-model="categoryAdd.recom" style="margin-left: 8px;">
            <el-radio value="0">不推荐</el-radio>
            <el-radio value="1">推荐</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否上架" label-width="20%" prop="status">
          <el-radio-group v-model="categoryAdd.status" style="margin-left: 8px;">
            <el-radio value="0">未上架</el-radio>
            <el-radio value="1">上架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片" label-width="20%">
          <el-upload v-model:file-list="categoryAdd.picList"
                     list-type="picture-card" :headers="headers"
                     :action="SERVER_ADDR + '/category/upload'" name="pic"
                     :before-upload="beforeAvatarUpload"
                     :on-success="handleUploadAdd"
          >
            <el-icon class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="AddShowFlag = false">取消</el-button>
          <el-button type="primary" @click="insert()">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- end增加提示框 -->

  <!-- start编辑提示框 -->
  <div>
    <el-dialog v-model="UpdateShowFlag" title="修改" width="800">
      <el-form :rules="rules"  :model="goodsUpdate">
        <el-form-item label="分类" label-width="20%">
          <el-cascader
              v-model="goodsUpdate.categoryId"
              :options="allParentList"
              :props="props"
              placeholder="请选择分类"
              clearable
              :value-on-clear="null"/>
        </el-form-item>
        <el-form-item label="名称" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="goodsUpdate.name"/>
        </el-form-item>
        <el-form-item label="描述" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="goodsUpdate.dscp"/>
        </el-form-item>
        <el-form-item label="售价" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="goodsUpdate.price"/>
        </el-form-item>
        <el-form-item label="标价" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="goodsUpdate.markPrice"/>
        </el-form-item>
        <el-form-item label="进价" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="goodsUpdate.purchasePrice"/>
        </el-form-item>
        <el-form-item label="颜色" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="goodsUpdate.color"/>
        </el-form-item>
        <el-form-item label="版本" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="goodsUpdate.version"/>
        </el-form-item>
        <el-form-item label="数量" label-width="20%" prop="dscp">
          <el-input autocomplete="off" v-model="goodsUpdate.count"/>
        </el-form-item>
        <el-form-item label="是否推荐" label-width="20%" prop="recom">
          <el-radio-group v-model="goodsUpdate.recom" style="margin-left: 8px;">
            <el-radio value="0">不推荐</el-radio>
            <el-radio value="1">推荐</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否上架" label-width="20%" prop="status">
          <el-radio-group v-model="goodsUpdate.status" style="margin-left: 8px;">
            <el-radio value="0">未上架</el-radio>
            <el-radio value="1">上架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片" label-width="20%">
          <el-upload v-model:file-list="goodsUpdate.picList"
                     list-type="picture-card"
                     :headers="headers"
                     :action="SERVER_ADDR + '/category/upload'" name="pic"
                     :before-upload="beforeAvatarUpload"
                     :on-success="handleUploadAdd"
          >
            <el-icon class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="UpdateShowFlag = false">取消</el-button>
          <el-button type="primary" @click="update()">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- end编辑提示框 -->
  <!-- 商品详情对话框开始 -->
  <div>
    <el-dialog v-model="detailDialogShow" title="商品详情" >
      <div v-if="detailDialogShow" style="border: 1px solid #ccc">
        <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
        />
        <Editor
            style="height: 500px; overflow-y: hidden;"
            v-model="goodsUpdate.detail"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogShow = false">取消</el-button>
          <el-button type="primary" @click="updateDetail">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 商品详情对话框结束 -->
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted, computed} from 'vue'
import {ElMessage} from 'element-plus';
import goodsApi from "@/api/goodsApi.js";
import categoryApi from "@/api/CategoryApi.js";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useTokenStore } from '@/stores/token';
import adminApi from "@/api/adminApi.js";
//是否显示商品的详情
const detailDialogShow = ref(false);
//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
//导出元素
const tokenStore = useTokenStore();
//解决token跟头像上传冲突，设置请求头
const headers = computed(() => {
  let token = tokenStore.tokenStr;
  return { token };
})


const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF:{
    uploadImage: {
      server:`${SERVER_ADDR.value}/goods/upload`,
      fieldName: 'pic',
      customInsert(resp, insertFn) {  // TS 语法
        // customInsert(res, insertFn) {                  // JS 语法
        // res 即服务端的返回结果
        let url =`${SERVER_ADDR.value}/goods/pic/${resp.data}`;
        // 从 res 中找到 url alt href ，然后插入图片
        insertFn(url)
      },
      headers: {
        token: tokenStore.tokenStr
      }
    }
  }
}
const mode = ref('default')
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
//显示商品详情的对话框
function showDetailDialog(goods) {
  goodsUpdate.value.id=goods.id;
  goodsUpdate.value.detail=goods.detail;
  goodsUpdate.value.picList=goods.picList;
  detailDialogShow.value = true;
}
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
//修改商品详情
function updateDetail(){
  goodsApi.update(goodsUpdate.value)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1200
          });
          detailDialogShow.value = false;
          goodsUpdate.value = ref(
              {
                id: null,
                name: '',
                dscp: '',
                detail: '',
                price: null,
                markPrice: null,
                purchasePrice: null,
                color: null,
                version: null,
                count: null,
                recom: '1',
                categoryId: null,
                status: '1',
                picList: []

              }
          )
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'danger',
            duration: 2000
          });
        }
      });
}
//级联选择器的配置选项
const props = {
  //给级联选择器绑定的数据和规定的key不一致时需要设置
  label: "name",//显示的信息
  value: "id",//值
  children: "childList",//子级
  emitPath: false
}
//父分类
const allParentList = ref([]);

//查询所有父分类
function selectAllParent() {
  categoryApi.selectAllParent().then(resp => {
    // console.log(resp);
    allParentList.value = resp.data;
  })
}

selectAllParent();
//分页信息
const pageInfo = ref({
  pages: 0,
  pageSize: 0,
  pageNum: 0
});
//搜索条件
const condition = ref({
  name: null,
  categoryId: null,
  status: null
});

//分页搜索
function selectByPage(pageNum) {
  goodsApi.selectByPage(condition.value, pageNum, 9)
      .then(resp => {
        pageInfo.value = resp.data;
        console.log(resp.data)
      });
}

selectByPage(1);
//显示增加对话框
const AddShowFlag = ref(false);
//新增商品信息
const categoryAdd = ref(
    {
      name: null,
      dscp: null,
      price: null,
      markPrice: null,
      purchasePrice: null,
      color: null,
      version: null,
      count: null,
      recom: '1',
      categoryId: null,
      status: '1',
      picList: []

    }
);

//保存增加信息
function insert() {
  //处理图片
  for (let i = 0; i < categoryAdd.value.picList.length; i++) {
    categoryAdd.value.picList[i].url = categoryAdd.value.picList[i].realName;
  }
      goodsApi.insert(categoryAdd.value)
          .then(resp => {
            if (resp.code == 10000) {
              ElMessage({
                message: resp.msg,
                type: 'success',
                duration: 1200
              });
              AddShowFlag.value = false;
              categoryAdd.value = {
                name: null,
                dscp: null,
                price: null,
                markPrice: null,
                purchasePrice: null,
                color: null,
                version: null,
                count: null,
                recom: '1',
                categoryId: null,
                status: '1',
                picList: []

              }
              selectByPage(pageInfo.value.pageNum);
            } else {
              ElMessage({
                message: resp.msg,
                type: 'danger',
                duration: 2000
              });
            }
          });

}


const cancelEvent = () => {
}

//删除部门数据
function del(id) {
  goodsApi.delete(id)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1200
          });
          selectByPage(1);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'danger',
            duration: 2000
          });
        }
      })
}


//显示编辑的提示框
const UpdateShowFlag = ref(false);

//被编辑商品的信息
const goodsUpdate = ref(
    {
      id: null,
      name: '',
      dscp: '',
      detail: '',
      price: null,
      markPrice: null,
      purchasePrice: null,
      color: null,
      version: null,
      count: null,
      recom: '1',
      categoryId: null,
      status: '1',
      picList: []

    }
)
//编辑部门信息
//回显数据
function selectById(id) {

  goodsApi.selectById(id)
      .then(resp => {
        if (resp.code == 10000) {
          goodsUpdate.value = resp.data;
          //处理图片
          for (let i = 0; i < goodsUpdate.value.picList.length; i++) {
            //保存图片真实的名字
            goodsUpdate.value.picList[i].realName = goodsUpdate.value.picList[i].url;
            //回显图片
            goodsUpdate.value.picList[i].url = `${SERVER_ADDR.value}/goods/pic/${goodsUpdate.value.picList[i].url} `;
          }
        }
        UpdateShowFlag.value = true;
      });
}

//保存更新数据
function update() {
  //处理图片
  for (let i = 0; i < goodsUpdate.value.picList.length; i++) {
    goodsUpdate.value.picList[i].url = goodsUpdate.value.picList[i].realName;
  }
  goodsApi.update(goodsUpdate.value)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1200
          });
          UpdateShowFlag.value = false;
          goodsUpdate.value = ref(
              {
                id: '',
                name: '',
                dscp: '',
                detail: '',
                price: null,
                markPrice: null,
                purchasePrice: null,
                color: null,
                version: null,
                count: null,
                recom: '1',
                categoryId: null,
                status: '1',
                picList: []

              }
          )
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'danger',
            duration: 2000
          });
        }
      });
}

//图片上传
function beforeAvatarUpload(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('头像仅支持jpg格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true;
}

//添加的成功的上传回调
function handleUploadAdd(resp, uploadFile, uploadFiles) {//resp-服务器的响应 uploadFile-上传的文件对象-和picList中对应的元素绑定
  if (resp.code === 10000) {
    ElMessage.success(resp.msg);
    uploadFile.url = `${SERVER_ADDR.value}/goods/pic/${resp.data}`;
    uploadFile.realName = resp.data;
  } else {
    ElMessage.error(resp.msg)
  }
}
//定义方法修改状态
function updateRecom(id, recom) {
  const updateRecomForm = {
    id,
    recom
  }
  goodsApi.update(updateRecomForm)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage.error(resp.msg);
        }
      })
}
function updateStatus(id, status) {
  const updateStatusForm = {
    id,
    status
  }
  goodsApi.update(updateStatusForm)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage.error(resp.msg);
        }
      })
}

// //表单验证
// const rules = {
//   name: [{required: true, message: '请输入商品名称', trigger: 'blur'}],
//   dscp: [{required: true, message: '请输入商品描述', trigger: 'blur'}]
// }
// const ruleFormRef = ref(null);
</script>

<style scoped>
/* 图片上传格式 */
.avatar-uploader,
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px dotted #dcdfe6;
  border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #060f1c;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>